// 1、引入express
const express = require('express');
// 2、引入router
const router = express.Router();
// 引入user模型
const User = require('../../models/User');
// 引入bcryptjs
const bcrypt = require('bcrypt');
// 引入 jwt
const jwt = require('jsonwebtoken');
// 引入密钥
const keys = require('../../config/keys');

const passport = require('passport');


/**
 * $route GET api/users/routerTest
 * @desc 返回请求的json数据        
 * @access 公有还是私有   public
 */
// 使用router的get方法
router.get('/routerTest', (req, res)=> {
  res.json({
    msg: '我是routerTest接口！'
  })
})
/**
 * $route GET api/users/sqlTest
 * @desc 返回请求的json数据 
 * @access 公有还是私有   public
 */
router.get('/sqlTest', (req, res)=> {
  User.findAll()
  .then(user => res.json(user))
  .catch(err => console.log(err))
})


/**
 * $route POST  api/users/register
 * @desc 返回请求的json数据        
 * @access 公有还是私有   public
 */
router.post('/register', (req, res)=> {
// 查询数据库中是否拥有邮箱
  User.findOne( {where: {email: req.body.email}})
  .then((user)=> {
    if(user) {
      return res.status(400)
                .json({ 
                  message:'邮箱已被注册！',
                  status: 400
                });

    }else {
      const newUser = new User({
        username: req.body.name,
        email: req.body.email,
        password: req.body.password,
        identity: req.body.identity
      })
      // 用户名不为空
      if (!req.body.name) {
        throw new Error('用户名不能为空');
      }
      // 加密密码
      bcrypt.genSalt(10, (err, salt)=> {
        bcrypt.hash(newUser.password, salt, (err, hash)=> {
          if(err) throw err;
          newUser.password = hash;
          newUser.save()
                 .then(user => {
                  res.status(200).json({
                    message: '注册成功！',
                    status: 200,
                    data: user
                  });
                 })
                 .catch(err => console.log(err))
        })
      })
      // newUser.save().then(user => res.json(user))
    }
  })
})
/**
 * $route POST  api/users/login
 * @desc 返回请求的json数据        
 * @access 公有还是私有   public
 */
router.post('/login', (req, res)=> {
  const username = req.body.username;
  const password = req.body.password;
  User.findOne({where: {email: username}})
    .then(user => {
      if(!user) {
        return res.status(404).json({
          success: false,
          message: '用户不存在！',
          status: 200,
        })
      }
      // 密码匹配
      bcrypt.compare(password, user.password)
        .then(isMatch => {
          if(isMatch) {
            // JWT使用
            // res.json({msg: '登录成功！'})
            // jwt.sign("规则",'加密名字（密钥）', "过期时间", '箭头函数【err,生城jwt字符串】')
            const rule = {
              id: user.id, 
              name: user.username,
              identity: user.identity
            }//使用id和name\identity作为规则
            // secret是密钥，在配置文件中
            jwt.sign(rule, keys.secretOrKey, {expiresIn: 3600}, (err, token)=> {
              if(err) throw err;
              res.status(200).json({
                success: true,
                status: 200,
                data: {
                  token: 'Bearer ' + token,
                  userInfo: {
                    id: user.id,
                    name: user.username,
                    password: user.password,
                    role: user.role,
                    roleIds: user.roleIds,
                    roleString: user.roleString,
                  }
                }
              })
            })
          }else {
            return res.status(400).json({password: '密码错误！'})
          }
        })
    })
})

/**
 * $route get  api/users/current
 * @desc return current user 验证JWT
 * @access 公有还是私有   private
 */
router.get("/current", passport.authenticate('jwt', {session: false}), (req, res)=> {
  res.json({
    id: req.user.id,
    name: req.user.username,
    email: req.user.email,
    identity: req.user.identity,
  })
})
/**
 * $route get  api/users/current
 * @desc return current user 验证JWT
 * @access 公有还是私有   private
 */
// router.get("/list", passport.authenticate('jwt', {session: false}), (req, res)=> {
//   res.json({
//     id: req.user.id,
//     name: req.user.username,
//     email: req.user.email,
//     identity: req.user.identity,
//   })
// })



// 4、导出
module.exports = router
